<template>
  <CommonModal
    :visible="visible"
    title="文件版本历史"
    width="60%"
    hide-footer
    @close="$emit('close')"
  >
    <div v-if="file" class="version-history-container">
      <h4>文件: {{ file.name }}</h4>
      <el-table :data="versions" style="width: 100%" v-loading="loading">
        <el-table-column prop="version" label="版本号" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.isLatest ? 'success' : ''">{{ scope.row.version }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="modifiedTime" label="修改时间" width="200"></el-table-column>
        <el-table-column prop="modifier" label="修改人" width="120"></el-table-column>
        <el-table-column prop="description" label="修改描述"></el-table-column>
        <el-table-column label="操作" width="180">
          <template #default="scope">
            <el-button size="small" @click="previewVersion(scope.row)">预览</el-button>
            <el-button size="small" type="warning" @click="revertVersion(scope.row)" :disabled="scope.row.isLatest">
              回退
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </CommonModal>
</template>

<script setup>
import { ref, watch, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import CommonModal from '../common/CommonModal.vue';

const props = defineProps({
  visible: Boolean,
  file: Object,
});
const emit = defineEmits(['close']);

const loading = ref(false);
const versions = ref([]);

const mockVersions = (fileId) => [
    { id: `v${fileId}-3`, version: 'V3.0', modifiedTime: '2023-10-05 11:00:00', modifier: '张研究员', description: '经"数据预处理"工作流处理生成', isLatest: true },
    { id: `v${fileId}-2`, version: 'V2.0', modifiedTime: '2023-10-04 16:20:00', modifier: '李博士', description: '修正了样本ID错误', isLatest: false },
    { id: `v${fileId}-1`, version: 'V1.0', modifiedTime: '2023-10-02 14:00:00', modifier: '张研究员', description: '初始上传', isLatest: false },
];

watch(() => props.visible, (newVal) => {
  if (newVal && props.file) {
    fetchVersions();
  }
});

const fetchVersions = () => {
  loading.value = true;
  setTimeout(() => {
    versions.value = mockVersions(props.file.id);
    loading.value = false;
  }, 300);
};

const previewVersion = (version) => {
  ElMessage.info(`正在准备预览版本 ${version.version}...`);
};

const revertVersion = (version) => {
  ElMessageBox.confirm(`确定要将文件回退到版本 ${version.version} 吗？当前最新版本将被覆盖。`, '警告', {
    confirmButtonText: '确定回退',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    ElMessage.success(`文件已成功回退到 ${version.version}`);
    emit('close');
    // 这里应该触发父组件刷新文件列表
  });
};
</script>

<style scoped>
.version-history-container {
  padding: 10px;
}
</style>
